﻿@using Transport.Data
@using Transport.Infrastructure
@model Transport.Areas.Administrator.Models.ParcelModel
@using (Html.BeginForm("Save", "Parcel", FormMethod.Post))
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/Areas/Administrator/Content/images/ico-catalog.png")" alt="" />
            @(Model.ParcelId > 0 ? "Sửa bưu phẩm" : "Tạo mới bưu phẩm")
        </div>
        <div class="options">
            <button type="submit" name="save" value="Save" tabindex="6" class="t-button">Lưu</button>
            @if (Model.ParcelId > 0)
            {
                if (WorkContext.Roles.Contains(RoleType.KTTruong))
                {
                    <a href="@Url.Action("Collected","Parcel")" tabindex="8" class="t-button">Quay về</a>
                }
                else
                {
                    <a href="@Url.Action("index","tracking")" tabindex="8" class="t-button">Quay về</a>
                }
            }
        </div>
    </div>
    
    @Html.HiddenFor(model => model.ParcelId)
    <div style="display: none">
        @Html.Telerik().NumericTextBoxFor(model => model.TotalCostHidden).MinValue(0).MaxValue(int.MaxValue).NumberGroupSeparator(".").DecimalDigits(2).DecimalSeparator(",")
    </div>
    <table width="99%">
        <tr>
            <td class="adminTitle">
                @Html.Label("Khách hàng")
            </td>
            <td class="adminData">
                MKH:
                @Html.TextBoxFor(model => model.CustomerCode, new{@style="width:50px; height:30px; padding-bottom:3px", @id="txtMKH"})
                @Html.DropDownListFor(model => model.CustomerId, new SelectList(Model.Customers, "CustomerId", "CustomerShortName"), "-Khách lẻ-", new { style = "width:215px" })
            </td>
        </tr>
        <tr>
            <td width="100" class="adminTitle">
                @Html.Label("Số vận đơn")
                <span class="field_required">*</span>
            </td>
            <td class="adminData">
                @Html.TextBoxFor(model => model.TrackingNumbers)
                @Html.ValidationMessageFor(model => model.TrackingNumbers)
            </td>
        </tr>
        <tr>
            <td width="100" class="adminTitle">
                @Html.Label("Ngày gửi")
                <span class="field_required">*</span>
            </td>
            <td style="padding-bottom:5px">
                @Html.Telerik().DateTimePickerFor(model => model.DateOfSending)
                @Html.ValidationMessageFor(model => model.DateOfSending)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.Label("Nơi đi")
                <span class="field_required">*</span>
            </td>
            <td class="adminData">
                @Html.DropDownGroupListFor(m => m.DeliverFromId, Model.StateProvincesFrom, "-Chọn-", new
                {
                    @data_val = "true",  // for Required Validation
                    @data_val_required = "Nơi đi là bắt buộc chọn." // for Required Validation
                })
                @Html.ValidationMessageFor(model => model.DeliverFromId, "Nơi đi là bắt buộc chọn.")
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.Label("Nơi đến")
                <span class="field_required">*</span>
            </td>
            <td class="adminData">
                @Html.DropDownGroupListFor(m => m.DeliverToId, Model.StateProvincesTo, "-Chọn-", new
                   {
                       @data_val = "true",  // for Required Validation
                       @data_val_required = "Nơi đến là bắt buộc chọn." // for Required Validation
                   })
                @Html.ValidationMessageFor(model => model.DeliverToId, "Nơi đến là bắt buộc chọn.")
            </td>
        </tr>
        <tr>
            <td width="100" class="adminTitle">
                @Html.Label("Địa chỉ nơi đến")
            </td>
            <td class="adminData">
                @Html.TextBoxFor(model => model.ToAddress)
                @Html.ValidationMessageFor(model => model.ToAddress)
            </td>
        </tr>
        <tr>
            <td width="100" class="adminTitle">
                @Html.Label("Phương thức thanh toán")
            </td>
            <td style="padding-bottom:10px">
                Nợ: @Html.RadioButtonFor(model => model.PaymentType, (int)Transport.Core.Models.Parcels.PaymentTypes.EnumPaymentTypes.Debt, Model.PaymentType == (int)Transport.Core.Models.Parcels.PaymentTypes.EnumPaymentTypes.Debt ? new { Checked = "checked" } : null)
                &nbsp;&nbsp;
                Tiền mặt: @Html.RadioButtonFor(model => model.PaymentType, (int)Transport.Core.Models.Parcels.PaymentTypes.EnumPaymentTypes.Cash, Model.PaymentType == (int)Transport.Core.Models.Parcels.PaymentTypes.EnumPaymentTypes.Cash ? new { Checked = "checked" } : null)
                &nbsp;&nbsp;
                Thu hộ: @Html.RadioButtonFor(model => model.PaymentType, (int)Transport.Core.Models.Parcels.PaymentTypes.EnumPaymentTypes.Collection, Model.PaymentType == (int)Transport.Core.Models.Parcels.PaymentTypes.EnumPaymentTypes.Collection ? new { Checked = "checked" } : null)
                @Html.ValidationMessageFor(model => model.PaymentType)
            </td>
        </tr>
        <tr>
            <td width="100" class="adminTitle">
                @Html.Label("Trọng lượng")
            </td>
            <td style="padding-bottom:10px">
                @(Html.Telerik().IntegerTextBoxFor(model => model.TotalWeight).ClientEvents(events => events.OnChange("ChangeTotalWeight")).MinValue(0).MaxValue(int.MaxValue).NumberGroupSeparator("."))
                @Html.ValidationMessageFor(model => model.TotalWeight)
            </td>
        </tr>
        <tr>
            <td width="100" class="adminTitle">
            </td>
            <td>
                @Html.CheckBoxFor(model => model.IsHandInput, new { id = "chkHandInput" }) Nhập tay
            </td>
        </tr>
        <tr>
            <td width="100" class="adminTitle">
                @Html.Label("Tổng tiền")
            </td>
            <td style="padding-bottom:10px" id="tdTotalCost">
                @Html.Telerik().NumericTextBoxFor(model => model.TotalCost).Name("TotalCost").ClientEvents(events => events.OnChange("ChangeTotalCost")).MinValue(0).MaxValue(int.MaxValue).NumberGroupSeparator(".").DecimalDigits(2).DecimalSeparator(",")
                @Html.ValidationMessageFor(model => model.TotalCost)
            </td>
        </tr>
        <tr>
            <td width="100" class="adminTitle">
                @Html.Label("Ghi chú")
            </td>
            <td class="adminData">
                @Html.TextBoxFor(model => model.Note)
                @Html.ValidationMessageFor(model => model.Note)
            </td>
        </tr>
        @if ( Model.ParcelId > 0 && (WorkContext.Roles.Contains(RoleType.KTTruong) || WorkContext.Roles.Contains(RoleType.TruongBuuCuc)))
        {
            <tr>
                <td width="100" class="adminTitle">
                    Duyệt và xác nhận giá
                </td>
                <td>
                    @Html.CheckBoxFor(model => model.IsApproval)
                </td>
            </tr>
            if (Model.PaymentType == (int)Transport.Core.Models.Parcels.PaymentTypes.EnumPaymentTypes.Collection || Model.PaymentType == (int)Transport.Core.Models.Parcels.PaymentTypes.EnumPaymentTypes.Cash)
            {
                <tr>
                    <td width="100" class="adminTitle">
                        Đã Thu
                    </td>
                    <td>
                        @Html.CheckBoxFor(model => model.Collected)
                    </td>
                </tr>
            }
        }
    </table>
}
@if (Model.ParcelId == -1)
{
    @Html.Osd().HiddenPopupWindow("Cảnh Báo", Helpers.DeleteConfirmMessageBox("Bạn có thực sự muốn xóa không", "Delete", "Tracking").ToHtmlString())
    <div class="section-header">
        <div class="title">
            <img alt="" src="/Areas/Administrator/Content/images/ico-catalog.png">
            Danh sách các định vị:
        </div>
        <div class="options">
            <a href="@Url.Action("Create", "Tracking", new { parcelId = Model.ParcelId})" tabindex="8" class="t-button">Tạo mới định vị cho bưu phẩm này</a>
        </div>
    </div>
    @(Html.Telerik().Grid<Transport.Areas.Administrator.Models.TrackingModel>()
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(x => x.TrackingId).Title("MS").ClientTemplate("<a href=\"/Administrator/Tracking/Edit/<#= TrackingId #>\"><#= 10000 + TrackingId #></a>")
                            .Width(100)
                            .Filterable(false);
            columns.Bound(x => x.TrackingNumbers).Title("Số Vận Đơn")
                .Width(150)
                .Filterable(false);
            columns.Bound(x => x.DeliverToName).Title("Hành Trình")
                .Width(250)
                .Filterable(false);
            columns.Bound(x => x.DateOfSending).Title("Ngày Gửi").Format("{0:H:mm - dd/MM/yyyy}")
                .Width(150)
                .Filterable(false);
            columns.Bound(x => x.PostOfficeName).Title("Vị Trí")
                .Filterable(false);
            columns.Bound(x => x.StatusName).Title("Trạng Thái")
                .Width(200)
                .Filterable(false);
            columns.Bound(p => p.TrackingId)
                .ClientTemplate("<a onclick='onMessageBoxActionDelete(<#= TrackingId #>)'><img src=\"/Content/Images/delete_16_16.png\" /></a>")
                .HtmlAttributes(new { style = "text-align:center" })
                .Title(string.Empty)
                .Width(100).Sortable(false)
                .Filterable(false);
        })
            .DataBinding(dataBinding => dataBinding.Ajax().Select("GetTrackings", "Tracking", new { parcelId = Model.ParcelId }))
        .Pageable()
        .Sortable()
        .Scrollable()
            .Groupable(grouping => grouping.Enabled(false))
        .Filterable()
    ) 
}
<script type="text/javascript">
    $(document).ready(function () {
        jQuery.validator.methods["date"] = function(value, element) { return true; };
        if ($('#txtMKH').val() != "") {
            $('#TrackingNumbers').focus();
        } else {
            $('#txtMKH').focus();
        }

        $('#TrackingNumbers').keypress(function (event) {
            if (event.keyCode == 13) {
                event.preventDefault();
            }
            else if (event.keyCode == 46) {
                $(this).val('');
            }
        });

        $('#chkHandInput').click(function () {
            if (this.checked) {
                EnableTotalCost();
            }
            else {
                DisableTotalCost();
            }

        });

        $('#CustomerId').change(function () {
            GetCost();
        });

        $('#DeliverToId').change(function () {
            GetCost();
        });

        $('#txtMKH').blur(function () {
            var customerCode = $(this).val();
            $.ajax({
                type: 'POST',
                dataType: "json",
                url: '@Url.Action("GetCustomer", "Parcel")',
                data: { customerCode: customerCode },
                success: function (data) {
                    if (!!data && data != '') {
                        $('#CustomerId').val(data);
                    }
                    else {
                        $('#CustomerId').val("");
                    }
                }
            });
        });
    });

    $(window).load(function () {
        if("@Model.IsHandInput" == "False") {
            DisableTotalCost();
        }
    });

    function DisableTotalCost() {
        var numberTextBox = $("#TotalCost").data("tTextBox");
        numberTextBox.disable();
    }

    function EnableTotalCost() {
        var numberTextBox = $("#TotalCost").data("tTextBox");
        numberTextBox.enable();
    }

    function GetCost() {
        var deliverFromId = $("#DeliverFromId").val();
        var deliverToId = $("#DeliverToId").val();
        var totalWeight = $("#TotalWeight").data("tTextBox").value();
        var customerId = $("#CustomerId").val();
        console.log(customerId);
        if (customerId == "") {
            customerId = 0;
        }
        if (!!deliverFromId && !!deliverToId && !!totalWeight && $("#chkHandInput").is(':checked') == false) {
            $.ajax({
                url: '@Url.Action("GetCost", "Parcel")',
                type: "POST",
                dataType: "json",
                // query will be the param used by your action method
                data: { deliverFromId: deliverFromId, deliverToId: deliverToId, totalWeight: totalWeight, customerId: customerId },
                success: function (data) {
                    var totalCost = $("#TotalCost").data("tTextBox");
                    totalCost.value(data);
                    var totalCostHidden = $("#TotalCostHidden").data("tTextBox");
                    totalCostHidden.value(data);
                }
            });
        }
    }

    function ChangeTotalWeight() {
        GetCost();
    }

    function ChangeTotalCost() {
        var totalCost = $("#TotalCost").data("tTextBox");
        var totalCostHidden = $("#TotalCostHidden").data("tTextBox");
        totalCostHidden.value(totalCost.value());
    }
</script>